package com.kkw.shoppingmall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.kkw.common.to.mq.OrderTo;
import com.kkw.common.to.mq.StockDetailTo;
import com.kkw.common.to.mq.StockLockedTo;
import com.kkw.common.utils.R;
import com.kkw.shoppingmall.ware.dao.WareSkuDao;
import com.kkw.shoppingmall.ware.entity.WareOrderTaskDetailEntity;
import com.kkw.shoppingmall.ware.entity.WareOrderTaskEntity;
import com.kkw.shoppingmall.ware.enume.OrderStatusEnum;
import com.kkw.shoppingmall.ware.feign.OrderFeignService;
import com.kkw.shoppingmall.ware.service.WareOrderTaskDetailService;
import com.kkw.shoppingmall.ware.service.WareOrderTaskService;
import com.kkw.shoppingmall.ware.service.WareSkuService;
import com.kkw.shoppingmall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author Kevin
 * @date 2021-06-18
 **/
@Service
@RabbitListener(queues = "stockReleaseStockQueue")
public class StockReleaseListener {
    @Autowired
    private WareSkuService wareSkuService;


    /**
     * 1）下单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚
     * * 之前锁定的库存就要自动解锁（本来是用seata来做分布式事务的 但是太慢了是个串行化操作了  所以使用mq来做）
     * 2）订单失败
     * 锁库存失败
     * 监听延迟队列里面的解锁库存的消息
     *
     * 只要解锁库存的消息失败。一定要告诉服务器解锁失败
     */
    @RabbitHandler
    void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {

        try {
            System.out.println("收到解锁库存的消息");
            wareSkuService.unLockStock(to);
            //multiple 是否是批量操作
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }


    @RabbitHandler
    void handleOrderCloseRelease(OrderTo order, Message message, Channel channel) throws IOException {

        try {
            System.out.println("订单关闭准备解锁库存");
            wareSkuService.unLockStock(order);
            //multiple 是否是批量操作
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
}
